
package com.viweb.storemanager.temp;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class LimitedFormatDocument extends PlainDocument {

    public static final byte DEFAULT = 0;
    public static final byte UPPER = 1;
    public static final byte LOWER = 2;
    public static final byte NUMBER = 3;
    private int limit;
    private byte style;

    public LimitedFormatDocument(int limit) {
        super();
        this.limit = limit;
    }

    public LimitedFormatDocument(int limit, byte style) {
        this(limit);
        this.setStyle(style);
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str != null && ((getLength() + str.length()) <= limit)) {
            if (this.getStyle() == NUMBER) {
                int i = -1;
                boolean isDigit = true;

                while (++i < str.length()) {
                    if (!Character.isDigit(str.charAt(i))) {
                        isDigit = !isDigit;
                        return;
                    }
                }

                super.insertString(offset, str, attr);
            } else if (this.getStyle() == UPPER) {
                super.insertString(offset, str.toUpperCase(), attr);
            } else if (this.getStyle() == LOWER) {
                super.insertString(offset, str.toLowerCase(), attr);
            } else {
                super.insertString(offset, str, attr);
            }
        }
    }

    public byte getStyle() {
        return style;
    }

    public void setStyle(byte style) {
        this.style = style;
    }
}